package com.navinfo.platform.trip.analysis.util;

import com.navinfo.platform.trip.common.enums.ProtocolEnum;
import com.navinfo.platform.trip.common.pojo.Point;
import org.apache.flink.streaming.runtime.operators.windowing.TimestampedValue;

import java.io.Serializable;
import java.util.Comparator;

/**
 * Point的比较器
 * @author: web
 * @date: 2020-08-27
 **/
public class PointComparator<T> implements Comparator<T>, Serializable {
    @Override
    public int compare(T v1, T v2) {
        int r = 0;
        if (v1 != null && v2 != null) {
            Point o1 = null;
            Point o2 = null;
            if(v1 instanceof TimestampedValue && v2 instanceof TimestampedValue){
                o1 = (Point) ((TimestampedValue)v1).getValue();
                o2 = (Point) ((TimestampedValue)v2).getValue();
            }

            if(v1 instanceof Point && v2 instanceof Point){
                o1 = (Point) v1;
                o2 = (Point) v2;
            }

            if(null!=o1 && null!=o2){
                //根据gpsTime排序
                if (o1.getGpsTime() > o2.getGpsTime()) {
                    r = 1;
                }else if (o1.getGpsTime() < o2.getGpsTime()) {
                    r = -1;
                }else{
                    //根据协议排序，将0200放天0f37前面
                    int t1 = ProtocolEnum.LOCATION.equals(o1.getProtocol()) ? 0 : 1;
                    int t2 = ProtocolEnum.LOCATION.equals(o2.getProtocol()) ? 0 : 1;
                    r = t1 - t2;

                    //最后根据流水号排序(相同协议)  r==0 <=> t1==t2
                    if (r == 0) {
                        int serial1 = o1.getSerialNumber();
                        int serial2 = o2.getSerialNumber();
                        if (serial1 > serial2) {
                            r = 1;
                        } else if (serial1 < serial2) {
                            r = -1;
                        }else{
                            //最后按转速排序，0f37流水号都为0
                            r = o1.getRotation() - o2.getRotation();
                        }
                    }
                }
            }
        }
        return r;
    }
}